﻿namespace EasyWeb.Validation
{
    using System;
    using System.ComponentModel.DataAnnotations;
    using System.Globalization;
    using System.Linq;

    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
    public class EWNameValidationAttribute : ValidationAttribute
    {
        public override string FormatErrorMessage(string name)
        {
            return string.Format(CultureInfo.CurrentCulture, EWValidationResources.Validation_Name, name);
        }

        public override bool IsValid(object value)
        {
            const string ALL = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_";
            const string NUMBER = "0123456789";

            var text = value as string;

            if (!string.IsNullOrEmpty(text))
            {
                var firstInvalid = NUMBER.IndexOf(text[0]) >= 0;
                var othersInvalid = text.Any(c => ALL.IndexOf(c, 0, ALL.Length) < 0);
                var valid = !(firstInvalid || othersInvalid);
                return !(firstInvalid || othersInvalid);
            }

            return false;
        }
    }
}
